#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash lapack-3.8.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e

yum install -y wget tar environment-modules
wget -t 40 -c -P $buildpath https://ghproxy.com/github.com/Reference-LAPACK/lapack/archive/v3.8.0.tar.gz -O $buildpath/lapack-3.8.0.tar.gz
tar -xvf $buildpath/lapack-3.8.0.tar.gz -C $buildpath # && rm -rf $buildpath/lapack-3.8.0.tar.gz
cp second_INT_ETIME.f.patch $buildpath/lapack-3.8.0/INSTALL
cp dsecnd_INT_ETIME.f.patch $buildpath/lapack-3.8.0/INSTALL
cd $buildpath/lapack-3.8.0
cp make.inc.example make.inc
sed -i -e 's/gcc/clang/g' \
    -e 's/FORTRAN = gfortran/FORTRAN = flang/g' \
    -e 's/LOADER   = gfortran/LOADER   = flang/g' \
    -e 's/librefblas.a/libblas.a/g' \
    -e 's/-frecursive//g' make.inc
cd INSTALL      
patch -p0 second_INT_ETIME.f second_INT_ETIME.f.patch
patch -p0 dsecnd_INT_ETIME.f dsecnd_INT_ETIME.f.patch 
cd ..
make -j$(nproc)
mkdir -p $installpath/lapack-3.8.0
cp *.a $installpath/lapack-3.8.0  
cat>"$installpath/lapack-3.8.0/lapack_modulefiles"<<EOF
#%Module1.0
conflict lapack
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set lapack \$pwd
setenv lapack \$lapack
prepend-path LD_LIBRARY_PATH \$lapack
EOF

#rm -rf $buildpath/lapack-3.8.0
